﻿from numpy import *

#从文件fname中读取dtype类型的cols列数据
#每行文本以split分隔,
#第2个返回要么是第一行标题，要么是最后一列标签
def file2matrix( fname, cols, dtype, split, title=False):
	fr = open(fname)
	lines = fr.readlines();
	titles = lines[0].strip().split(split)	
	lines = lines[1:]
	
	count = len(lines)
	mat = empty((count, cols), dtype)	
	labels = []
	index = 0	
	for line in lines:
		line = line.strip()
		list = line.split(split)		
		mat[index, : ] = list[0:cols]		
		labels.append(list[-1])
		index+=1	
	if title: return mat, titles
	else: return mat, labels
	
#利用已知的数据集data和对应标签labels对x进行分类
#k邻近算法参数
def kClassfy(x, data, labels, k):
	count = data.shape[0]
	dif = tile(x, (count, 1)) - data
	dif = dif**2
	distances = dif.sum(axis = 1)
	distances = distances**0.5
	sorted = distances.argsort();
	maps ={}
	for i in range(k):
		label = labels[sorted[i]]
		maps[label] = maps.get(label, 0) + 1
	li = list(maps.items())
	li.sort(key=lambda x:(-x[1]))
	print( li[0][0] ) 

#newvalue = (oldvalue-min)/(max-min)
def autoNorm(dataset):
	return
	
if __name__ == '__main__' :
	mat,labels = file2matrix("data_ActOrLov.txt", 2, float32, ' ')
	kClassfy([18, 90], mat, labels, 5);   #得到结果1 为爱情片
